
import 'package:animated_search_bar/animated_search_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_deer/game/iview/game_search_list_iview.dart';
import 'package:flutter_deer/game/models/game_item_entity.dart';
import 'package:flutter_deer/game/presenter/game_search_list_presenter.dart';
import 'package:flutter_deer/game/provider/game_search_list_provider.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/util/image_utils.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/widgets/fadein_text.dart';
import 'package:flutter_deer/widgets/load_image.dart';
import 'package:flutter_deer/widgets/my_card.dart';
import 'package:flutter_deer/widgets/my_refresh_list.dart';
import 'package:flutter_deer/widgets/state_layout.dart';
import 'package:lottie/lottie.dart';
import 'package:provider/provider.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:text_scroll/text_scroll.dart';

class GameSearchPage extends StatefulWidget {

  const GameSearchPage({super.key});

  @override
  _GameSearchPageState createState() => _GameSearchPageState();
}

class _GameSearchPageState extends State<GameSearchPage> with SingleTickerProviderStateMixin,BasePageMixin<GameSearchPage, PowerPresenter>, AutomaticKeepAliveClientMixin implements GameSearchListIMvpView {

  GameSearchListProvider listProvider = GameSearchListProvider();
  final GlobalKey _bodyKey = GlobalKey();
  late GameSearchListPresenter gameSearchListPresenter;
  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(this);
    gameSearchListPresenter = new GameSearchListPresenter();
    powerPresenter.requestPresenter([gameSearchListPresenter]);
    return powerPresenter;
  }

  @override
  void setAllGameItems(List<GameItemEntity>? items){
    listProvider.setGameItems(items);
  }

  @override
  void setGameItems(List<GameItemEntity>? items){
    listProvider.setGameItems(items);
  }

  @override
  void initState() {
    super.initState();
    if(mounted){
      _onRefresh();
    }
  }

  @override
  void dispose() {
    listProvider.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  final TextEditingController _controller = TextEditingController();

  Future<dynamic> _onRefresh() async {
    Future.delayed(Duration(seconds: 1),()=>{gameSearchListPresenter.search(_controller.text.nullSafe)});
  }

  Future<dynamic> _loadMore() async {
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final Color? iconColor = ThemeUtils.getIconColor(context);
    return ChangeNotifierProvider<GameSearchListProvider>(
        create: (_) => listProvider,
        child:  Consumer<GameSearchListProvider>(
        builder: (_,provider,child){
          return  Scaffold(
            key: _bodyKey,
            appBar: AppBar(
              leading: IconButton(
                onPressed: () async {
                  FocusManager.instance.primaryFocus?.unfocus();
                  final isBack = await Navigator.maybePop(context);
                  if (!isBack) {
                    await SystemNavigator.pop();
                  }
                },
                tooltip: '${DeerLocalizations.of(context)!.back.nullSafe}',
                padding: EdgeInsets.all(12.0),
                icon: Image.asset(
                  Constant.backImg,
                  color: ThemeUtils.getIconColor(context),
                  height: 24,
                  width: 24,
                ),
              ),
              title: AnimatedSearchBar(
                  label: '${DeerLocalizations.of(context)!.inputTeamName.nullSafe}',
                  controller: _controller,
                  searchIcon: LoadAssetImage(
                    'goods/search',
                    key: const Key('searchIcon'),
                    width: 24.0,
                    height: 24.0,
                    color: iconColor,
                  ),
                  closeIcon: LoadAssetImage(
                    'goods/search',
                    key: const Key('closeIcon'),
                    width: 24.0,
                    height: 24.0,
                    color: iconColor,
                  ),
                  labelStyle: TextStyle(fontSize: 16,color: context.isDark ? Colours.text_gray : Colours.text,),
                  searchStyle: TextStyle(color: context.isDark ? Colours.text_gray : Colours.text,),
                  cursorColor: context.isDark ? Colours.text_gray : Colours.text,
                  textInputAction: TextInputAction.done,
                  searchDecoration: InputDecoration(
                    hintText: '${DeerLocalizations.of(context)!.search.nullSafe}',
                    alignLabelWithHint: true,
                    fillColor: Colors.white,
                    focusColor: Colors.white,
                    hintStyle: TextStyle(color: context.isDark ? Colours.text_gray : Colours.text,),
                    border: InputBorder.none,
                  ),
                  onFieldSubmitted: (value){
                    listProvider.setLoading();
                    gameSearchListPresenter.search(value);
                  }
              ),
            ),
            body: listProvider.stateType==StateType.loading?StateLayout(type: StateType.loading):(listProvider.list!.length>0?DeerListView(
          itemCount: listProvider.list!.length,
          stateType: listProvider.stateType!,
          onRefresh: _onRefresh,
          loadMore: _loadMore,
          hasMore: false,
                itemBuilder: (_, index) {
                  final GameItemEntity item = listProvider.list!.elementAt(index);
                  print('${item.teamOneName}');
                  return Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10.0,vertical: 5),
                      child: MyCard(
                          child: Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 5),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Gaps.vGap5,
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Container(
                                          width: MediaQuery.of(context).size.width/2-50,
                                          child: TextScroll(item.name.nullSafe,mode: TextScrollMode.endless,pauseBetween: Duration(milliseconds: 500),)
                                      ),
                                      Text('${DeerLocalizations.of(context)!.playingTime.nullSafe}:'+item!.playDate.nullSafe.substring(5)+' '+item.playTime.nullSafe)
                                    ],
                                  ),
                                  Gaps.vGap5,
                                  Divider(height: 1.0,indent: 0.0),
                                  Gaps.vGap10,
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: [
                                      Container(
                                        width: (MediaQuery.of(context).size.width-80)/2,
                                        child: Column(
                                          children: [
                                            Image(image:ImageUtils.getImageProvider(Constant.imageServerHost+'${item.teamOne!.image.nullSafe}',holderImg: 'shop/tx'),width: 30,height: 30,),
                                            Gaps.vGap12,
                                            TextScroll(item.teamOne!.name.nullSafe,mode: TextScrollMode.endless,pauseBetween: Duration(milliseconds: 500),)
                                          ],
                                        ),
                                      ),
                                      LoadAssetImage('logo',format:ImageFormat.gif,width:50,height:50),
                                      Container(
                                        width: (MediaQuery.of(context).size.width-80)/2,
                                        child: Column(
                                          children: [
                                            Image(image:ImageUtils.getImageProvider(Constant.imageServerHost+'${item.teamTwo!.image.nullSafe}',holderImg: 'shop/tx'),width: 30,height: 30,),
                                            Gaps.vGap12,
                                            TextScroll(item.teamTwo!.name.nullSafe,mode: TextScrollMode.endless,pauseBetween: Duration(milliseconds: 500),)
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                  Gaps.vGap5
                                ],
                              )
                          )
                      )
                  );
                }
            ):Container(
                width: MediaQuery.of(context).size.width,
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Lottie.asset('assets/lottie/no_football_game.json',width: MediaQuery.of(context).size.width/3,fit: BoxFit.cover),
                  Gaps.vGap8,
                  FadeInText(text: '${DeerLocalizations.of(context)!.noGame.nullSafe}')
                ],
              ),
            ),
          ))
          );
        }
   ));
  }

  @override
  bool get wantKeepAlive => false;
}
